package com.ymatou.utils.database;

import com.ymt.core.tool.Logger;
import org.apache.ibatis.session.SqlSession;

import java.io.IOException;
import java.util.List;

public class SqlManager {

    public SqlSession session = null;
    private MyBatisUtil mbu = new MyBatisUtil();
    private String senv = null;

    public SqlManager(String env) {
        this.senv = env;
        if (env == null) {
            try {
                this.session = this.mbu.initialFactory("ymtsit");
            } catch (IOException var4) {
                var4.printStackTrace();
            }
        } else {
            try {
                this.session = this.mbu.initialFactory(env);
            } catch (IOException var3) {
                var3.printStackTrace();
            }
        }

        try {
            if (this.session == null || this.session.getConnection().isClosed()) {
                this.session = this.mbu.initialFactory(env);
            }
        } catch (Exception var5) {
            var5.printStackTrace();
        }

    }

    public SqlSession getSession() {
        return this.session;
    }

    public boolean isClosed() {
        boolean isclose = true;

        try {
            isclose = this.session.getConnection().isClosed();
        } catch (Exception var3) {
            Logger.debug("没有获取到 sql session 连接状态");
        }

        return isclose;
    }

    public List getSelectResults(String mapperMethodName, Object param) {
        List results = this.session.selectList(mapperMethodName, param);
        return results;
    }

    public int update(String mapperMethodName, Object param) {
        int result = this.session.update(mapperMethodName, param);
        return result;
    }

    public int delete(String mapperMethodName, Object param) {
        int result = this.session.delete(mapperMethodName, param);
        return result;
    }

    public int insert(String mapperMethodName, Object param) {
        int result = this.session.insert(mapperMethodName, param);
        return result;
    }

    public List<List<?>> getSpResults(String mapperMethodName, Object param) {
        List<List<?>> results = this.session.selectList(mapperMethodName, param);
        return results;
    }

    public void commit() {
        this.session.commit(true);
    }

    public void rollback() {
        this.session.rollback(true);
    }

    public void close() {
        this.mbu.close();
    }

    public String getEnv() {
        return this.senv;
    }
}
